#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
FastAPI主应用文件
仅包含app实例和启动配置
"""

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import atexit
import shutil
from pathlib import Path

from docx_image_extract_url import router as docx_router

# 创建FastAPI应用实例
app = FastAPI(
    title="DocX图片提取API",
    description="从DocX文件中提取图片并返回URL",
    version="1.0.0"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 创建必要目录
static_dir = Path("static/images")
static_dir.mkdir(parents=True, exist_ok=True)

doc_dir = Path("static/documents")
doc_dir.mkdir(parents=True, exist_ok=True)

temp_dir = Path("temp")
temp_dir.mkdir(exist_ok=True)

# 清理临时文件的函数
def cleanup_temp_files():
    """清理临时文件夹"""
    try:
        if temp_dir.exists():
            shutil.rmtree(temp_dir)
            temp_dir.mkdir(exist_ok=True)
    except Exception as e:
        print(f"清理临时文件失败: {e}")

# 注册退出时清理函数
atexit.register(cleanup_temp_files)

# 挂载静态文件服务
app.mount("/static", StaticFiles(directory="static"), name="static")

# 注册路由
app.include_router(docx_router, prefix="/api/v1", tags=["DocX处理"])

@app.get("/")
async def root():
    """根路径"""
    return {
        "message": "doc/DocX图片提取API服务",
        "version": "1.0.0",
        "docs": "/docs"
    }

@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy"}

if __name__ == "__main__":
    # 启动服务器
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    )
